package cn.luderson.application;

import java.util.Date;
import java.util.Properties;

import cn.luderson.daos.DAO;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;

public class JDBCOperation {
    public static Logger logger1 = Logger.getLogger(JDBCOperation.class);
    public static void main(String args[]) {
        
        logger1.trace("=========== 启动 =============");
        String users[];
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties");
        Properties pro = new Properties();
        try {
            pro.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        String usersStr = pro.getProperty("checkusers");
        users = usersStr.split(",");
        for (int i = 0; i < users.length; i++) {
            check( users[i] );
        }
        
        logger1.trace("=========== 全部结束 =============");

    }


    public static void check(String user) {
        
        // get new record
        String recordIdStr =  DAO.getLatestCardIdAsString(user);
        // logger1.trace("recordIdStr = " + recordIdStr );
        // 
        if(recordIdStr.equals("__NOTHING__")){
            logger1.trace("用户 "+user+" 没有历史打卡数据");
            return ;
        }
        // 
        Date cardDate = DAO.getCardDate(recordIdStr);
        Date todayDate = new Date();
        // logger1.trace("cardDate = " + cardDate);
        // logger1.trace("todayDate = " + todayDate);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String cardDateStr = sdf.format(cardDate);
        String todayDateStr = sdf.format(todayDate);
        if( cardDateStr.equals(todayDateStr) ){
            logger1.trace("用户 "+user+" 今天已经打卡 ");
            return ;
        }

        // 
        logger1.trace(""+user+" 未打卡，准备打卡操作");
        // 生成主键
        String newRecordId = DAO.computeLatestRecordIdAsString();
        logger1.trace("newRecordId="+newRecordId );
        // add a empty rocord
        DAO.addEmpryRecord(newRecordId);
        logger1.trace("新增今日打卡记录成功");
        // 复制数据
        DAO.copyRecord(recordIdStr,newRecordId); //
        logger1.trace("处理今日打卡记录成功");
        // update today 
        DAO.updateHealthCardToday(user);
        logger1.trace("修改今日打卡标记成功");
        
    }
}
